package com.zcxy360.sandtable.shiro;

import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.zcxy360.sandtable.domain.User;
import com.zcxy360.sandtable.service.UserService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private DefaultWebSessionManager sessionManager;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(userService.getRolesByUsername(username));
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
		for(Session session:sessions){
			String loginUsername = String.valueOf(session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));//获得session中已经登录用户的名字
			if(username.equals(loginUsername)){  //这里的username也就是当前登录的username
				session.setTimeout(0);  //这里就把session清除，
			}
		}
		User user = userService.getUserByUsername(username);
		if (user == null) {
			throw new UnknownAccountException("用户名不存在:"+username);
		}
		if(user.getIsLocked()) {
			throw new LockedAccountException("用户已锁定");
		}
		Session session = SecurityUtils.getSubject().getSession();
		session.setAttribute("user", user);
		String name=  user.getUsername()!=null?user.getUsername():user.getPhone()!=null?user.getPhone():user.getIdCard();
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(name,
				user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
		return authenticationInfo;
	}

}